<template>
    <el-row>
        <!--详情页-->
        <el-descriptions v-if="displayType==='info'"  direction="vertical" :column="3" border>
            <el-descriptions-item label="用户名">{{userinfo.username}}</el-descriptions-item>
            <el-descriptions-item label="性别">{{userinfo.sex}}</el-descriptions-item>
            <el-descriptions-item label="邮箱">{{userinfo.email}}</el-descriptions-item>
            <el-descriptions-item label="组织路径">
                <el-tag size="medium">{{userinfo.pathname}}</el-tag>
            </el-descriptions-item>
            <el-descriptions-item label="角色">
                <el-tag size="medium">{{userinfo.roleName}}</el-tag>
            </el-descriptions-item>
            <el-descriptions-item label="上级领导"><el-tag size="medium">{{userinfo.leaderName}}</el-tag></el-descriptions-item>
            <el-descriptions-item label="上次登陆IP"> 
                <el-tag v-if="userinfo.loginIp!==null&&userinfo.loginIp!==undefined&&userinfo.loginIp!==''" size="medium">{{userinfo.loginIp}}</el-tag>
                <el-tag v-else size="medium">暂未查询到其IP地址捏</el-tag>
            </el-descriptions-item>
            <el-descriptions-item label="用户创建时间">{{userinfo.createTime}}</el-descriptions-item>
        </el-descriptions>
        <!--修改页-->
        <el-form v-if="displayType==='edit'" label-width="85px" class="infoInput" ref="editForm" :model="userinfo" :rules="rules" >
            <el-row :span="24">
                <el-col :span="12">
                    <el-form-item prop="username">
                        <span slot="label">
                            <span class="span-box">
                            <el-tooltip style="diaplay:inline" effect="dark" content="用户名唯一，不能与已存在的用户名重复" placement="top">
                                <i class="el-icon-question" />
                                </el-tooltip>
                            <span>用户名</span>
                            </span>
                        </span>
                        <el-input v-model="userinfo.username"></el-input>
                    </el-form-item>
                </el-col>
                <el-col :span="12">
                    <el-form-item>
                        <span slot="label">
                            <span class="span-box">
                            <el-tooltip style="diaplay:inline" effect="dark" content="只能上传不超过5mb的jpg/png文件，再次点击可重新上传" placement="top">
                                <i class="el-icon-question" />
                                </el-tooltip>
                            <span>头像</span>
                            </span>
                        </span>
                        <el-upload class="avatar-uploader" action="/api/user/imgUpload" :show-file-list="false"
                        :on-success="handleAvatarSuccess" :before-upload="beforeAvatarUpload">
                            <img v-if="userinfo.avatar" :src="userinfo.avatar" class="avatar">
                            <i v-else class="el-icon-plus avatar-uploader-icon"></i>
                        </el-upload>
                    </el-form-item>
                </el-col>
            </el-row>
            <el-row :span="24">
                <el-col :span="12">
                    <el-form-item prop="password">
                        <span slot="label">
                            <span class="span-box">
                            <el-tooltip style="diaplay:inline" effect="dark" content="密码可由英文数字下划线组成，且大于六位" placement="top">
                                <i class="el-icon-question" />
                                </el-tooltip>
                            <span>密码</span>
                            </span>
                        </span>
                        <el-input v-model="userinfo.password" size="medium"></el-input>
                    </el-form-item>
                </el-col>
                <el-col :span="12">
                    <el-form-item prop="salt">
                        <span slot="label">
                            <span class="span-box">
                            <el-tooltip style="diaplay:inline" effect="dark" content="盐值为密码的加密密钥,可由英文数字下划线组成" placement="top">
                                <i class="el-icon-question" />
                                </el-tooltip>
                            <span>盐值</span>
                            </span>
                        </span>
                        <el-input v-model="userinfo.salt" size="medium"></el-input>
                    </el-form-item>
                </el-col>
            </el-row>
            <el-row :span="24">
                <el-col :span="12">
                    <el-form-item label="性别">
                        <el-radio-group v-model="userinfo.sex">
                            <el-radio label="男"></el-radio>
                            <el-radio label="女"></el-radio>
                        </el-radio-group>
                    </el-form-item>
                </el-col>
                <el-col :span="12">
                    <el-form-item label="状态">
                      <el-switch active-color="#13ce66" v-model="userinfo.status" active-value="1" inactive-value="0"
                                 inactive-color="#ff4949"></el-switch>
                    </el-form-item>
                </el-col>
            </el-row>
            <el-row :span="24">
                <el-col :span="12">
                    <el-form-item label="手机号码" prop="phone">
                        <el-input v-model="userinfo.phone" size="medium"></el-input>
                    </el-form-item>
                </el-col>
                <el-col :span="12">
                    <el-form-item label="邮箱" prop="email">
                        <el-input v-model="userinfo.email"></el-input>
                    </el-form-item>
                </el-col>
            </el-row>
            <el-row :span="24">
                <el-col :span="12">
                    <el-form-item label="所属部门" prop="orgName">
                        <el-select ref="orgEditSelect" v-model="userinfo.orgName" clearable placeholder="请选择部门">
                            <el-option style="display:none" label="请选择" value="0"></el-option>
                            <el-tree style="display:'inline-block'" ref="tree" :data="orgTree" :props="defaultProps" @node-click="setUserOrg($event,'edit')"></el-tree>
                        </el-select>
                    </el-form-item>
                </el-col>
                <el-col :span="12">
                    <el-form-item label="当前角色" prop="roleName">
                        <el-select v-model="userinfo.roleName" clearable placeholder="请选择角色" @visible-change="getAllRole()" @change="setUserRole($event,'edit')">
                            <el-option v-for="item in roleOptions"
                            :key="item.id" :label="item.roleName" :value="item.id">
                            </el-option>
                        </el-select>
                    </el-form-item>
                </el-col>
            </el-row>
            <el-row :span="24">
                <el-col :span="24">
                    <el-form-item label="备注">
                        <el-input type="textarea" v-model="userinfo.remark"></el-input>
                    </el-form-item>
                </el-col>
            </el-row>
            <el-row>
               <el-col>
                   <div class="inlineBtn">
                      <el-button size="medium" type="primary" @click="updateSubmit">提交</el-button>
                      <el-button size="medium" @click="noUpdate">关 闭</el-button>
                   </div>
               </el-col>
            </el-row>
        </el-form>
        <!--新增页-->
        <el-form v-if="displayType==='add'" label-width="85px" class="infoInput" :rules="rules" :model="newuser" ref="addForm">
            <el-row :span="24">
                <el-col :span="12">
                    <el-form-item prop="username">
                        <span slot="label">
                            <span class="span-box">
                            <el-tooltip style="diaplay:inline" effect="dark" content="用户名唯一，不能与已存在的用户名重复" placement="top">
                                <i class="el-icon-question" />
                                </el-tooltip>
                            <span>用户名</span>
                            </span>
                        </span>
                        <el-input v-model="newuser.username" size="medium"></el-input>
                    </el-form-item>
                </el-col>
                <el-col :span="12">
                    <el-form-item label="">
                        <span slot="label">
                            <span class="span-box">
                            <el-tooltip style="diaplay:inline" effect="dark" content="只能上传不超过2mb的jpg/png文件，再次点击可重新上传" placement="top">
                                <i class="el-icon-question" />
                                </el-tooltip>
                            <span>头像</span>
                            </span>
                        </span>
                        <el-upload class="avatar-uploader" action="/api/user/imgUpload"
                        :show-file-list="false" :on-success="handleAvatarSuccess" :before-upload="beforeAvatarUpload">
                            <img v-if="newuser.avatar" :src="newuser.avatar" class="avatar">
                            <i v-else class="el-icon-plus avatar-uploader-icon"></i>
                        </el-upload>
                    </el-form-item>
                </el-col>
            </el-row>

            <el-row :span="24">
                <el-col :span="12">
                    <el-form-item prop="password">
                        <span slot="label">
                            <span class="span-box">
                            <el-tooltip style="diaplay:inline" effect="dark" content="密码可由英文数字下划线组成，且大于六位" placement="top">
                                <i class="el-icon-question" />
                                </el-tooltip>
                            <span>密码</span>
                            </span>
                        </span>
                        <el-input v-model="newuser.password" size="medium"></el-input>
                    </el-form-item>
                </el-col>
                <el-col :span="12">
                    <el-form-item prop="salt">
                        <span slot="label">
                            <span class="span-box">
                            <el-tooltip style="diaplay:inline" effect="dark" content="盐值为密码的加密密钥,可由英文数字下划线组成" placement="top">
                                <i class="el-icon-question" />
                                </el-tooltip>
                            <span>盐值</span>
                            </span>
                        </span>
                        <el-input v-model="newuser.salt" size="medium"></el-input>
                    </el-form-item>
                </el-col>
            </el-row>

            <el-row :span="24">
                <el-col :span="12">
                    <el-form-item label="状态">
                        <el-switch v-model="newuser.status" size="medium"></el-switch>
                    </el-form-item>
                </el-col>
                <el-col :span="12">
                    <el-form-item label="性别">
                        <el-radio-group v-model="newuser.sex" size="medium">
                            <el-radio label="男"></el-radio>
                            <el-radio label="女"></el-radio>
                        </el-radio-group>
                    </el-form-item>
                </el-col>
            </el-row>

            <el-row :span="24">
                <el-col :span="12">
                    <el-form-item label="手机" prop="phone">
                        <el-input v-model="newuser.phone" size="medium"></el-input>
                    </el-form-item>
                </el-col>
                <el-col :span="12">
                    <el-form-item label="邮箱" prop="email">
                        <el-input v-model="newuser.email" size="medium"></el-input>
                    </el-form-item>
                </el-col>
            </el-row>
			
            <el-row :span="24">
                <el-col :span="12">
                    <el-form-item label="所属部门" prop="orgName">
                        <el-select ref="orgAddSelect" size="medium" v-model="newuser.orgName" clearable placeholder="请选择部门">
                            <el-option style="display:none" label="请选择" value="0"></el-option>
                            <el-tree style="display:'inline-block'" ref="tree" :data="orgTree" :props="defaultProps" @node-click="setUserOrg($event,'add')"></el-tree>
                        </el-select>
                    </el-form-item>
                </el-col>
                <el-col :span="12">
                    <el-form-item label="当前角色" prop="roleName">
                        <el-select v-model="newuser.roleName" clearable placeholder="请选择角色" @visible-change="getAllRole()" @change="setUserRole($event,'add')" size="medium">
                            <el-option
                            v-for="item in roleOptions"
                            :key="item.id"
                            :label="item.roleName"
                            :value="item.id">
                            </el-option>
                        </el-select>
                    </el-form-item>
                </el-col>
            </el-row>
            
			<el-row :span="24">
                <el-col :span="24">
                    <el-form-item label="备注">
                <el-input type="textarea" v-model="userinfo.remark"></el-input>
            </el-form-item>
                </el-col>
            </el-row>

            <el-row>
              <el-col>
                  <div class="inlineBtn">
                      <el-button size="medium" type="primary" @click="addSubmit">提交</el-button>
                      <el-button size="medium" @click="noUpdate">关 闭</el-button>
                  </div>
              </el-col>
            </el-row>
		</el-form>
    </el-row>
</template>

<script>
export default {
    data(){
        //用户名深度校验规则
        var validateUname = (rule, value, callback) => {
            //用户名校验：中英文数字下划线，组合单一都可
            const unameReg=/^[\u4E00-\u9FA5A-Za-z0-9_]+$/ // eslint-disable-line
            if(!unameReg.test(value)){
                callback(new Error('用户名只能由中英文、数字、下划线组成'));
            }else if(this.usernameList.includes(value)){
                callback(new Error('用户名唯一，不能与已存在的用户名重复！'));
            }else{
                callback();
            }
        };
        //密码深度校验规则
        var validatePwd = (rule, value, callback) => {
            //密码/盐值校验：英文数字下划线，组合单一都可
            const pwdReg=/^[A-Za-z0-9_]+$/ 
            if(!pwdReg.test(value)){
                callback(new Error('密码只能由英文、数字、下划线组成'));
            }else{
                callback();
            }
        };
        //盐值深度校验规则
        var validateSalt = (rule, value, callback) => {
            const pwdReg=/^[A-Za-z0-9]+$/ 
            if(!pwdReg.test(value)){
                callback(new Error('盐值只能由英文和数字组成'));
            }else{
                callback();
            }
        };
        //电话号码深度校验规则
        var validatePhone = (rule, value, callback) => {
            if(!this.sa.isPhone(value)){
                callback(new Error('电话号码格式错误！'));
            }else{
                callback();
            }
        };
        //邮箱深度校验规则
        var validateEmail = (rule, value, callback) => {
            if(!this.sa.isEmail(value)){
                callback(new Error('邮箱格式错误！'));
            }else{
                callback();
            }
        };
        return{
            newuser: {	
                username: '',	// 从菜单配置文件里传递过来的参数
                password: '',
                status:true,
                phone: '',
                orgName: '',
                roleName:'',
                sex: '男',
                avatar: '',//头像地址
                salt:''//盐
            },
            //表单校验规则
            rules:{
                username: [
                    { required: true, message: '请输入用户名', trigger: 'blur' },
                    { min: 0, max: 12, message: '长度在 1 到 12 个字符', trigger: 'blur' },
                    { validator: validateUname, trigger: 'blur'}
                ],
                password: [
                    { required: true, message: '请输入用户密码', trigger: 'blur' },
                    { min: 6, max: 12, message: '长度在 6 到 12 个字符', trigger: 'blur' },
                    { validator: validatePwd, trigger: 'blur'}
                ],
                salt: [
                    { required: true, message: '请输入盐值', trigger: 'blur' },
                    { validator: validateSalt, trigger: 'blur'}
                ],
                phone: [
                    { required: true, message: '请输入电话号码', trigger: 'blur' },
                    { validator: validatePhone, trigger: 'blur'}
                ],
                email: [
                    { required: true, message: '请输入邮箱', trigger: 'blur' },
                    { validator: validateEmail, trigger: 'blur'}
                ],
                orgName: [
                    { required: true, message: '请选择用户所属部门', trigger: 'change' }
                ],
                roleName: [
                    { required: true, message: '请选择用户所属角色', trigger: 'change' }
                ],
            },
            show:false,
            userinfo:JSON.parse(this.info),
            usernameList:[],
            orgOptions: [],
            defaultProps: {
            children: 'children',
            label: 'label'
			},
            selectShow:"true",
            roleOptions: [],
        }
    },
    //display:info展示用户信息页，edit展示用户修改页
    props:['info','displayType','orgTree'],
    methods:{
        //修改提交
        updateSubmit() {
            if(!this.checkForm('editForm')){
                return
            }
            this.sa.loading("修改中...");
            let params=this.userinfo;
            params.status=params.status==true?1:0
            console.log(params);
            this.request('/api/user/update',params).then(res=>{
              if(!res){return}
              this.sa.hideloading();
              this.$message.success('修改成功');
              this.$bus.$emit('updateUserInfo',this.userinfo)//去修改父组件的数据喽..
            })
        },
        //新增提交
        addSubmit(){
            if(!this.checkForm('addForm')){
                return
            }
            let params=this.newuser;
            console.log(params);      
            params.status=params.status==true||''?1:0
            //console.log(params);
            this.sa.loading("添加用户中...");
            this.request('/api/user/add',params).then(res=>{
              if(!res){return}
              this.sa.hideloading();
              this.$bus.$emit('addUser')//去修改父组件的数据喽..
              this.$message.success("添加成功")
            })
        },
        //表单提交前置校验
        checkForm(formName){
            let flag;
            this.$refs[formName].validate((valid) => {
                if (valid) {
                    flag=true;
                    return true;
                } else {
                    flag=false
                    return false;
                }
            });
            return flag
        },
        //获取全部角色
        getAllRole(){
            //let params=;
            this.request('/api/role/getAllRole').then(res=>{
              if(!res){return}
              //console.log(res);
              if(this.sa.isNotNull(res.data)){
                this.roleOptions=res.data
              }
            })
        },
        //修改/新增用户角色id，在下拉框被重新选中后就会执行
        //可能会有点问题，但仔细理了下不修改直接关闭，不触发全局事件总线，父组件的数据不受影响，再次点击修改数据也会重新加载，上一次未提交的操作也影响不到
        setUserRole(params,type){
            if(type==='edit'){
                //当前选中的value
                //console.log(params);
                this.userinfo.roleid=params
            }
            if(type==='add'){
                this.newuser.roleid=params
            }
            
        },
        //修改/新增用户组织id，在下拉框被重新选中后就会执行
        setUserOrg(params,type){
            //console.log(params);
            //console.log(type);
            //当前选中的value
            if(params.parentId!=="0"){
                if(type==='edit'){
                    this.userinfo.orgid=params.id
                    this.userinfo.orgName=params.label
                    this.$refs.orgEditSelect.blur();
                }
                if(type==='add'){
                    this.newuser.orgid=params.id
                    this.newuser.orgName=params.label
                    this.$refs.orgAddSelect.blur();
                }
            }else{
                this.openWarning("请选择具体部门！")
            }
            //console.log(this.userinfo);
        },
        //头像上传成功后的回调
        handleAvatarSuccess(res, file) {
            //console.log("上传成功：");
            console.log(res);
            //console.log(file);
            this.newuser.avatar =this.zm.handleImgPath(res.data);//回传的头像地址
            this.userinfo.avatar =this.zm.handleImgPath(res.data);//回传的头像地址
            console.log(this.userinfo.avatar)
            this.$message.success("上传成功");
        },
        //头像上传前的校验
        beforeAvatarUpload(file) {
            const isJPG = file.type === 'image/jpeg'||'image/png';
            const isLt2M = file.size / 1024 / 1024 < 2;
            return new Promise((resolve, reject) => {
                if(!isJPG) {
                    this.$message.error('上传头像图片只能是 JPG/PNG 格式!');
                    reject(file);
                } else if(!isLt2M) {
                    this.$message.error('上传头像图片大小不能超过 2MB!');
                    reject(file);
                }else {
                    resolve(file);
                }
	        });
        },
        //取消修改
        noUpdate(){
            this.$bus.$emit("noUpdate")
        },
        //弹出警告提示框，参数为警告信息
        openWarning(msg) {
            this.$notify({
                title: '警告',
                message: msg,
                type: 'warning'
            });
        },
    },
    mounted(){
        //console.log("userinfo组件挂载");
        console.log(this.userinfo);
        this.request('/api/user/getAllUsername').then(res=>{
          if(!res){return}
          this.usernameList=res.data
          if(this.displayType=='edit'){
            let index=this.usernameList.indexOf(this.userinfo.username)
            this.usernameList.splice(index,index+1)
          }
        })
    },
    beforeDestroy(){
        //console.log("userinfo组件被销毁了..");
    }
}
</script>

<style>
/*操作按钮 */
.inlineBtn {
    text-align:center
}
/*表单input框样式控制 */
.infoInput >div>div>div>div>div>input{
  width:90%;
}
/**头像上传相关样式 */
 .avatar-uploader .el-upload {
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
  }
  .avatar-uploader .el-upload:hover {
    border-color: #409EFF;
  }
  .avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 100px;
    height: 100px;
    line-height: 100px;/**+号和边框距离 */
    text-align: center;
  }
  .avatar {
    width: 100px;
    height: 100px;
    display: block;
  }
</style>